package bb.lanxing;

import static bb.lanxing.common.config.Constants.FOLDER_CRASH;
import static bb.lanxing.service.SyncTaskService.TASK_SYNC_POI_PHOTO;
import static bb.lanxing.service.SyncTaskService.TASK_SYNC_WORKOUT;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.platform.comapi.map.MapBundleKey;
import com.blankj.utilcode.util.AppUtils;
import com.clj.fastble.BleManager;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.shiply.processor.DiffPkgHandler;
import com.tencent.shiply.processor.OriginBasePkgFile;
import com.tencent.tauth.Tencent;
import com.tencent.upgrade.bean.UpgradeConfig;
import com.tencent.upgrade.core.DefaultUpgradeStrategyRequestCallback;
import com.tencent.upgrade.core.UpgradeManager;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;

import bb.lanxing.activity.login.AccountLoginActivity;
import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.config.UmInitConfig;
import bb.lanxing.common.messager.MessageSender;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.base.BaseApplication;
import bb.lanxing.lib.devices.api.DeviceApplication;
import bb.lanxing.lib.devices.api.DeviceManager;
import bb.lanxing.lib.devices.api.DeviceProvider;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.manager.LevelPermissionMgr;
import bb.lanxing.manager.RemoteServiceManager;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.manager.SystemLocationManager;
import bb.lanxing.manager.SystemSensorManager;
import bb.lanxing.model.database.City;
import bb.lanxing.model.database.LaunchBanner;
import bb.lanxing.model.database.Province;
import bb.lanxing.model.database.User;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.json.WeatherData;
import bb.lanxing.mvp.model.LaunchBannerModelImpl;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.network.ThirdPartyClient;
import bb.lanxing.service.DownloadService;
import bb.lanxing.service.PostQueueService;
import bb.lanxing.service.SyncTaskService;
import bb.lanxing.service.WorkoutRemoteService;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.BiCiCoorConverter;
import bb.lanxing.util.DistanceUtil;
import bb.lanxing.util.Enums;
import bb.lanxing.util.JsonUtil;
import bb.lanxing.util.Log;
import bb.lanxing.util.MessageUtil;
import bb.lanxing.util.NetworkUtil;
import bb.lanxing.util.ProcessUtil;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.util.WebkitUtil;
import bb.lanxing.util.debug.CrashHandler;
import bb.lanxing.util.debug.OtherProcessCrashListener;
import bb.lanxing.util.upgrade.ShiplyLogger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class App extends BaseApplication implements DeviceApplication {
	final static private String TAG = "App";

	public static boolean isManagersInit;

	public static Enums.NetworkState networkState;
	public static int screenWidth = 0;
	public static int screenHeight = 0;
	private static App mContext;
	private final AtomicInteger mSequenceGenerator = new AtomicInteger();
	private final AppLifecycle.OnStatueChangedListener onStatueChangedListener = new AppLifecycle.OnStatueChangedListener() {
		@Override public void onForeground() {
			Log.v(TAG, "AppLifecycle, onForeground");
			RemoteServiceManager.getInstance().onForeground();
		}

		@Override public void onBackground(boolean z) {
			Log.v(TAG, "AppLifecycle, onBackground");
			RemoteServiceManager.getInstance().onBackground();
			boolean isSporting = RemoteServiceManager.getInstance().isSporting();
			Log.i(Constants.TAG, "onBackground: isSportMode = " + isSporting);
			if (isSporting || !z) {
				App.this.reduceMemory(isSporting);
			}
		}
	};
	public SharedPreferences trackConf = null;
	public boolean isSdkInit = false;
	public IWXAPI wxapi;
	private boolean debugMode = false;
	private MessageSender messageSender;

	private String processName;
	private User signinUser;
	private boolean superVersion;
	private boolean isAppLaunched = false;
	private int httpDomain;
	private String userAgent;
	private String umengAppKey;
	private String umengChannel;
	private int mBatteryPercent = 0;
	private int privateMessageCount = 0;
	private boolean batterySavingVersion;
	private BroadcastReceiver mBatteryReceiver = null;
	private BroadcastReceiver mBluetoothStateReceiver = null;
	private long lastUploadBiciLocationTimestamp;
	private long lastUploadLocationTimestamp;
	private LatLng uploadedLocation;
	private boolean userDataChanged = false;

	// bes begin
	public static App getInstance() {
		return mContext;
	}

	public static App getContext() {
		return mContext;
	}

	public void setUserDataChanged(boolean userDataChanged) {
		this.userDataChanged = userDataChanged;
	}

	public int getVersionCode() {
		return BuildConfig.VERSION_CODE;
	}

	public String getVersionName() {
		return BuildConfig.VERSION_NAME;
	}

	@Override protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		mContext = this;
	}

	// bes end

	@Override public void onCreate() {
		super.onCreate();

		// 初始化processName
		String processName = ProcessUtil.getProcessName();
		this.processName = processName;
		this.processName = TextUtils.isEmpty(processName) ? "" : this.processName;

		// 初始化
		DeviceHelper.setDeviceApplication(mContext);
		initMacro();
		Log.init();
		Log.logi(Constants.TAG, "[App] onCreate <<<<");
		initSystemInfo();

		// 初始化sharePreference
		RemoteSharedPreference.getInstance();

		// 初始化数据库
		// initDataBase();
		LitePal.initialize(this);

		// 在使用SDK各组件之前初始化context信息，传入ApplicationContext
		SDKInitializer.setAgreePrivacy(mContext, true);
		SDKInitializer.initialize(mContext);
		// 自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
		// 包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
		SDKInitializer.setCoordType(CoordType.BD09LL);

		// 初始化友盟
		youMengInit();

		// 初始化lifeCycle
		initAppForMainProcess();

		if (SharedManager.getInstance().isUseAgreementAgree()) {
			initAfterUserAgree();
		}
		checkPermission();
		if (App.getContext().isAppForeground()) {
			handleProvinceImport();
			handleCityImport();
		}

		BleManager.getInstance().init(BaseApplication.get());
		if (BuildConfig.BUILD_TYPE.equals("release")) {
			new Handler().postDelayed(() -> {
				initShiplyUpgradeSDK();
				autoDetectUpgrade();
			}, 8000);
		}
	}

	public void handleCityImport() {
		City c = LitePal.findFirst(City.class);
		if (c == null) {
			City.importDatas();
		}
	}

	public void handleProvinceImport() {
		Province p = LitePal.findFirst(Province.class);
		if (p == null) {
			Province.importDatas();
		}
	}

	public void initAfterUserAgree() {
		// if (!ProcessUtil.getProcessName().equals(getContext().getPackageName())) {
		// return;
		// }
		try {
			SystemSensorManager.getInstance().init(this);
			registerBluetoothStateReceiver();
			DeviceContext.startAndRefreshAutoConnector();

			MyHttpClient.init(getUserAgent());
			initNetwork();
			XZDeviceHelper.init(getApplicationContext());

			Log.e(TAG, "initAfterUserAgree");
			initWeixinApi();

			// if (!BaiduLocationManager.getInstance().isOpening()) {
			// BaiduLocationManager.getInstance().openBaiduGps();
			// }
			// disable getui
			// initGetuiPush();

			requestWeatherData();
			// requestLaunchVersionInfo();
			this.isSdkInit = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initGetuiPush() {
		PackageManager packageManager = getPackageManager();
		boolean readStoragePerm = packageManager.checkPermission(RxPermissionUtil.getReadStoragePermission(), getPackageName()) == PackageManager.PERMISSION_GRANTED;
		boolean readPhoneStatePerm = packageManager.checkPermission(RxPermissionUtil.getReadPhoneStatePermission(), getPackageName()) == PackageManager.PERMISSION_GRANTED;
		/* if (readStoragePerm && readPhoneStatePerm) */
		{
			MessageUtil.triggerGetui(true);
		}
	}

	private void initShiplyUpgradeSDK() {
		// Map<String, String> map = new HashMap<>();
		// map.put("UserAge", "20");
		UpgradeConfig.Builder builder = new UpgradeConfig.Builder();
		builder.appId(BuildConfig.SHIPLY_APPID) // 测试项目 appid
			.appKey(BuildConfig.SHIPLY_APPKEY) // 测试项目 appkey
			.systemVersion(String.valueOf(Build.VERSION.SDK_INT)) // 用户手机系统版本，用于匹配shiply前端创建任务时设置的系统版本下发条件
			/* .customParams(map) */ // 自定义属性键值对，用于匹配shiply前端创建任务时设置的自定义下发条件
			.cacheExpireTime(1000 * 60 * 60 * 6) // 1 灰度策略的缓存时长（ms），如果不设置，默认缓存时长为1天
			.internalInitMMKVForRDelivery(true) // 是否由sdk内部初始化mmkv(调用MMKV.initialize()),业务方如果已经初始化过mmkv，可以设置为false
			.userId("xxtest") // 用户Id,用于匹配shiply前端创建的任务中的体验名单以及下发条件中的用户号码包
			.printInternalLog(true).customLogger(new ShiplyLogger()); // 日志实现接口，建议对接到业务方的日志接口，方便排查问题

		builder.diffPkgHandler(new DiffPkgHandler());// 差量APK处理器，负责差量包下载与合成，业务方如果不使用差量包能力，可以不用设置
		builder.basePkgFileForDiffUpgrade(new OriginBasePkgFile());// 表示基于原始文件生成差量包，不支持渠道包差量
		// builder.basePkgFileForDiffUpgrade(new ZipDataBasePkgFile());//
		// 表示基于渠道包文件的纯数据区域生成差量包，支持渠道包差量，业务方的渠道号是写在V2签名区域时请使用这种方式
		UpgradeManager.getInstance().init(App.this, builder.build());
	}

	private void autoDetectUpgrade() {
		UpgradeManager.getInstance().checkUpgrade(false, null, new DefaultUpgradeStrategyRequestCallback());
	}

	public void exitApp() {
		Log.logv(TAG, "---Lanxing--- exitApp <<<<");
		if (RemoteServiceManager.getInstance().isSporting()) {
			RemoteServiceManager.getInstance().stopSport();
		}
		// BaiduLocationManager.getInstance().closeBaiduGps();
		RemoteServiceManager.getInstance().closeBLE();
		RemoteServiceManager.getInstance().unbindWorkoutService();
		try {
			stopService(new Intent(this, WorkoutRemoteService.class));
		} catch (Exception e) {
			e.printStackTrace();
		}
		SharedManager.getInstance().commit();
		RemoteSharedPreference.getInstance().commit();
		unregisterBatteryReceiver();
		unregisterBluetoothStateReceiver();
		releaseInstances();
		this.isAppLaunched = false;
		Log.logv(TAG, "---Lanxing--- exitApp >>>>");
	}

	private void releaseInstances() {
		SystemLocationManager.terminate();
		SystemSensorManager.terminate();
		RemoteSharedPreference.terminate();
	}

	@Override public void onTerminate() {
		super.onTerminate();
		Log.logd(TAG, "[App] onTerminate");

		AppLifecycle.release(this);
	}

	private void initSystemInfo() {
		StringBuilder sb = new StringBuilder();
		try {
			PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 128);
			Bundle bundle = packageInfo.applicationInfo.metaData;
			String str = null;
			setUmengChannel(bundle != null ? bundle.getString("UMENG_CHANNEL") : null);
			if (bundle != null) {
				str = bundle.getString("UMENG_APPKEY");
			}
			setUmengAppKey(str);
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
				sb.append(URLEncoder.encode(Build.BRAND, StandardCharsets.UTF_8));
			} else {
				sb.append(URLEncoder.encode(Build.BRAND));
			}
			sb.append(" , ");
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
				sb.append(URLEncoder.encode(Build.MODEL, StandardCharsets.UTF_8));
			} else {
				sb.append(URLEncoder.encode(Build.MODEL));
			}
			sb.append(" , ");
			sb.append(Build.VERSION.RELEASE);
			sb.append(" , ");
			sb.append(packageInfo.versionName);
			setUserAgent(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getDeviceInfo() {
		StringBuilder sb = new StringBuilder("Android: ");
		sb.append(Build.VERSION.RELEASE);
		sb.append(", ");
		sb.append(Build.BRAND);
		sb.append(", ");
		sb.append(Build.MODEL);
		try {
			PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			sb.append("; Version: ");
			sb.append(packageInfo.versionName);
			sb.append(", ");
			sb.append(packageInfo.versionCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public boolean isDebugMode() {
		return this.debugMode;
	}

	public boolean isSuperVersion() {
		return this.superVersion;
	}

	public boolean isBatterySavingVersion() {
		return this.batterySavingVersion;
	}

	public int getHttpDomain() {
		return this.httpDomain;
	}

	public boolean isAppForeground() {
		return AppUtils.isAppForeground();
	}

	private void initWeixinApi() {
		this.wxapi = WXAPIFactory.createWXAPI(this, Constants.SOCIAL_WECHAT_APP_ID, true);
		new Thread(() -> App.this.wxapi.registerApp(Constants.SOCIAL_WECHAT_APP_ID)).start();
	}

	public void requestLaunchVersionInfo() {
		MyHttpClient.requestLaunchVersionInfo(new Callback() {
			@Override public void onFailure(@NonNull Call call, @NonNull IOException iOException) {
				if (App.this.getMessageSender() != null) {
					App.this.getMessageSender().sendMessage(R.id.msg_check_version_expired);
				}
				iOException.printStackTrace();
			}

			@Override public void onResponse(@NonNull Call call, @NonNull Response response) {
				try {
					String string = response.body().string();
					Log.d(TAG, " response : " + response + " body : " + string);
					JSONObject jSONObject = new JSONObject(string);
					long longValue = JsonUtil.getLongValue("time_unix", jSONObject);
					if (longValue != 0) {
						SharedManager.getInstance().setServersAndSysTimeSub(longValue - System.currentTimeMillis());
					}
					String string2 = jSONObject.getJSONObject("hosts").getString("maps_ip");
					if (!TextUtils.isEmpty(string2)) {
						SharedManager.getInstance().setGoogleHost(string2);
					}
					App.this.setPrivateMessageCount(jSONObject.getInt("unreadPrivateMessageCount"));
					// if (jSONObject.has("xzb_update_time")) {
					// long j = SharedManager.getInstance().getLong(TopicsDataUtils.KEY_TOPIC_UPDATE_TIME, 0L);
					// long j2 = jSONObject.getLong("xzb_update_time");
					// if (j < j2) {
					// SharedManager.getInstance().setValue(TopicsDataUtils.KEY_TOPIC_UPDATE_TIME, Long.valueOf(j2));
					// TopicsDataUtils.setHasNewReply(true);
					// }
					// }
					if (jSONObject.has("home_page_online")) {
						List parseArray = JSON.parseArray(jSONObject.getString("home_page_online"), LaunchBanner.class);
						App app = App.this;
						if (parseArray == null) {
							parseArray = new ArrayList(0);
						}
						app.refreshLaunchInfo(parseArray);
					}
					// FirmwareUpgradeManager.getInstance().checkFirmware(jSONObject.getJSONObject("bici_firmware"));
					App.this.setFwVersion(jSONObject);
					if (jSONObject.has("discovery_ad_position")) {
						SharedManager.getInstance().setValue(SPConstant.DISCOVERY_AD_ARRAY_JSON, jSONObject.getString("discovery_ad_position"));
					}
					if (!jSONObject.has("goods_operator")) {
						return;
					}
					JSONObject jSONObject2 = jSONObject.getJSONObject("goods_operator");
					int i = jSONObject2.getInt("badge_type");
					String string3 = jSONObject2.getString("badge_name");
					Long valueOf = jSONObject2.getLong("badge_time");
					if (i == 3) {
						SharedManager.getInstance().setValue(SPConstant.MAIN_TAB_SHOP_BADGE_NAME, string3);
					} else if (i == 2 && SharedManager.getInstance().getLong(SPConstant.MAIN_TAB_SHOP_BADGE_TIME, 0L) != valueOf) {
						SharedManager.getInstance().setValue(SPConstant.MAIN_TAB_SHOP_BADGE_TIME, valueOf);
						SharedManager.getInstance().setValue(SPConstant.MAIN_TAB_SHOP_BADGE_CLICK, false);
					}
					SharedManager.getInstance().setValue(SPConstant.MAIN_TAB_SHOP_BADGE_TYPE, i);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, SharedManager.getInstance().getLong(SharedManager.KEY_LASTET_PROVINCE_ID, -1L));
	}

	public void refreshLaunchInfo(List<LaunchBanner> list) {
		if (list != null) {
			LaunchBannerModelImpl launchBannerModelImpl = new LaunchBannerModelImpl();
			launchBannerModelImpl.updateLaunchBanner(list);
			if (networkState == Enums.NetworkState.wifi) {
				for (LaunchBanner launchBanner : list) {
					launchBannerModelImpl.downloadBannerImage(launchBanner);
				}
			}
			LatLng earth2Baidu = BiCiCoorConverter.earth2Baidu(SharedManager.getInstance().getCurLatLngWithMP());
			launchBannerModelImpl.requestProvinceId(earth2Baidu.latitude, earth2Baidu.longitude);
		}
	}

	public void setFwVersion(JSONObject jSONObject) throws JSONException {
		if (jSONObject.has("qi_firmware")) {
			JSONObject jSONObject2 = jSONObject.getJSONObject("qi_firmware");
			String string = jSONObject2.getString("qi_version_name");
			jSONObject2.getString("qi_update_log");
			jSONObject2.getInt("qi_version_id");
			String string2 = jSONObject2.getString("qi_file_url");
			File file = new File(AppFileUtils.buildExternalDirectoryPath("download"), string2.substring(string2.lastIndexOf(File.separatorChar) + 1));
			XZDeviceHelper.setFirmwarePath(6, file.getPath());
			XZDeviceHelper.setVersion(6, string);
			DownloadService.download(this, null, string2, file.getAbsolutePath());
		}
	}

	public void requestWeatherData() {
		Observable.create(new NetSubscribe(ThirdPartyClient.requestWeatherData(SharedManager.getInstance().getCurLatLngWithMP()))).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).map(str -> {
			try {
				return new WeatherData(new JSONObject(str));
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
			@Override public void onCompleted() {
			}

			@Override public void onError(Throwable th) {
			}

			@Override public void onNext(WeatherData weatherData) {
				Log.v(TAG, "from internet: windSpeed=" + weatherData.getWindSpeed() + ", windDeg=" + weatherData.getWindDeg() + ", pressure=" + weatherData.getPressure());
				RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_WEATHER_WIND_SPEED, (float) weatherData.getWindSpeed());
				RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_WEATHER_WIND_DEG, (float) weatherData.getWindDeg());
				RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_WEATHER_PRESSURE, (float) weatherData.getPressure());
			}
		});
	}

	private void initNetwork() {
		int connectedType = NetworkUtil.getConnectedType(this);
		if (connectedType == 0) {
			networkState = Enums.NetworkState.mobile;
		} else if (connectedType == 1) {
			networkState = Enums.NetworkState.wifi;
		} else {
			networkState = Enums.NetworkState.disable;
		}
	}

	public void showLongMessage(final String str) {
		this.handler.post(() -> Toast.makeText(App.this.getApplicationContext(), str, Toast.LENGTH_LONG).show());
	}

	public void showMessage(final String str) {
		this.handler.post(() -> Toast.makeText(App.this.getApplicationContext(), str, Toast.LENGTH_SHORT).show());
	}

	public void showMessage(final int i) {
		this.handler.post(() -> Toast.makeText(App.this.getApplicationContext(), i, Toast.LENGTH_SHORT).show());
	}

	/**
	 * 获取请求标识
	 */
	public int getTag() {
		return mSequenceGenerator.incrementAndGet();
	}

	private void youMengInit() {
		// UMConfigure.preInit(this, "657a9a7895b14f599dffd353", "随便");
		// 友盟正式初始化
		UmInitConfig umInitConfig = new UmInitConfig();
		umInitConfig.UMinit(getApplicationContext());
		// QQ官方sdk授权
		Tencent.setIsPermissionGranted(true);
	}

	private void initAppForMainProcess() {
		AppLifecycle.init(this);
		AppLifecycle.get().registerOnStatueChangedListener(this.onStatueChangedListener);
		this.messageSender = new MessageSender();
		// registerActivityLifecycleCallbacks(new PushHelper.ActivityLifecycleListener());
	}

	public MessageSender getMessageSender() {
		return this.messageSender;
	}

	public void uploadDeviceToken() {
	}

	public void userSignin() {
		showMessage(R.string.mine_toast_login_first);
		AccountLoginActivity.launchLoginActivity(getContext(), Intent.FLAG_ACTIVITY_NEW_TASK);
	}

	public boolean isUserSignin() {
		User userByUid;
		if (!SharedManager.getInstance().isSignoutFlag()) {
			Log.d(Constants.TAG, "isUserSignin = false");
			return false;
		}

		// 如果数据没有变化的话,不需要重新加载
		if (this.signinUser != null && !userDataChanged) {
			return true;
		}
		userDataChanged = false;
		long userId = SharedManager.getInstance().getUserId();
		if (userId == 0 || (userByUid = User.getUserByUid(userId)) == null) {
			return false;
		}

		this.signinUser = userByUid;
		return true;
	}

	public long getUserId() {
		if (isUserSignin()) {
			return SharedManager.getInstance().getUserId();
		}
		return 0L;
	}

	public User getSigninUser() {
		return this.signinUser;
	}

	public void setSigninUser(User user) {
		if (null != user) {
			// 用户退出登录的话,不显示头像url,退出登录没清相关数据库
			if (!SharedManager.getInstance().isSignoutFlag()) {
				user.setPhotoUrl("");
			}
		}
		this.signinUser = user;
	}

	public void cleanSigninState() {
		SharedManager.getInstance().setSignoutFlag(false);
		SharedManager.getInstance().setEventId(0);
		RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_UPLOAD_LOCATION, false);
		SharedManager.getInstance().setUserAgreement(false);
		SharedManager.getInstance().setValue(SharedManager.KEY_MAIN_CLUB_AUTH, 0);
		SharedManager.getInstance().setSyncQQHealth(false);
		SharedManager.getInstance().setUserId(0);
		getContext().setSigninUser(null);
		App.getContext().stopRemoteService(WorkoutRemoteService.class);
		RemoteServiceManager.getInstance().closeBLE();
		MyHttpClient.clearCookie();
		WebkitUtil.clearCookies(this);
	}

	public String getUserPhone() {
		if (!isUserSignin() || TextUtils.isEmpty(this.signinUser.getPhone())) {
			return "";
		}
		return this.signinUser.getPhone();
	}

	private void initMacro() {
		try {
			ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo(getPackageName(), 128);
			this.debugMode = applicationInfo.metaData.getBoolean("DEBUG_MODE", false);
			this.superVersion = applicationInfo.metaData.getBoolean("SUPER_VERSION", false);
			// this.batterySavingVersion = applicationInfo.metaData.getBoolean("BATTERY_SAVING_VERSION", false);

			// if (EnginUtil.isAPKDebugable(this)) {
			// this.debugMode = SharedManager.getInstance().getBoolean("debugMode", this.debugMode);
			// }

			int i = SharedManager.getInstance().getInt("httpDomain", 0);
			if (i == 0) {
				SharedManager.getInstance().setValue("httpDomain", 5);
				i = 5;
			}

			if (i >= 1) {
				this.httpDomain = i;
			}
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	void reduceMemory(boolean z) {
		Log.logi(Constants.TAG, "reduceMemory: severe = " + z);
		if (z) {
		}
		System.gc();
	}

	private void checkPermission() {
		if (RxPermissionUtil.getInstance().checkPermission(this, RxPermissionUtil.getLocationStoragePermission())) {
			initManagersWithPermissions();
		}
	}

	private void initCrashHandler() {
		String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(FOLDER_CRASH);
		if (android.text.TextUtils.isEmpty(buildExternalDirectoryPath)) {
			return;
		}
		Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(new File(buildExternalDirectoryPath), new OtherProcessCrashListener(this)));
	}

	public void initManagersWithPermissions() {
		try {
			if (!isManagersInit) {
				initCrashHandler();
				// OsmMapUtil.initOsmPath();
				LevelPermissionMgr.getInstance().init();
				// FeedbackAPI.init(this, Constants.ALI_BAI_CHUAN_FEEDBACK_KEY,
				// Constants.ALI_BAI_CHUAN_FEEDBACK_KEY_SECURE);
				isManagersInit = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void disconnectDevice(int i) {
		XZDeviceHelper.disconnect(i);
	}

	@Override public DeviceManager getDeviceManager() {
		return DeviceContext.getDeviceManager();
	}

	@Override public DeviceProvider getDeviceProvider() {
		return DeviceContext.getDeviceProvider();
	}

	public void setUmengChannel(String str) {
		this.umengChannel = str;
	}

	public void setPrivateMessageCount(int i) {
		this.privateMessageCount = i;
	}

	public int getPhoneBattery() {
		return this.mBatteryPercent;
	}

	public void setUmengAppKey(String str) {
		this.umengAppKey = str;
	}

	public String getUserAgent() {
		return this.userAgent;
	}

	public void setUserAgent(String str) {
		this.userAgent = str;
	}

	public void uploadSelfLocation(LatLng latLng, DisplayPoint displayPoint, Workout workout, final int status, int interval, Callback callback) {
		if (callback == null) {
			callback = new BiCiCallback() {
				@Override public void onResponseString(@NonNull String string) throws JSONException {
				}
			};
		}
		// 上传服务器的时候，GPS全部切换为百度标准
		latLng = BiCiCoorConverter.earth2Baidu(latLng);
		MyHttpClient.uploadMyLoation(callback, latLng, displayPoint, workout, status, interval);
		this.lastUploadLocationTimestamp = System.currentTimeMillis();
		this.uploadedLocation = latLng;
	}

	public void uploadMyLocationIfNeed(LatLng latLng, DisplayPoint displayPoint, Workout workout, int i, boolean z, Callback callback) {
		int i2;
		if (networkState != Enums.NetworkState.disable && RemoteSharedPreference.getInstance().getBoolean(SPConstant.KEY_UPLOAD_LOCATION, false)) {
			if (z) {
				uploadSelfLocation(latLng, displayPoint, workout, i, 60000, callback);
			} else if (System.currentTimeMillis() - this.lastUploadLocationTimestamp > 60000 && isUserSignin()) {
				if (getContext().isBatterySavingVersion()) {
					int selfLocationUploadIntervalWithMP = SharedManager.getInstance().getSelfLocationUploadIntervalWithMP();
					if (selfLocationUploadIntervalWithMP < 0) {
						return;
					}
					i2 = selfLocationUploadIntervalWithMP;
				} else {
					i2 = 60000;
				}
				LatLng latLng2 = this.uploadedLocation;
				if (latLng2 != null && DistanceUtil.get(latLng2, latLng) < 50.0d) {
					return;
				}
				uploadSelfLocation(latLng, displayPoint, workout, i, i2, callback);
			}
		}
	}

	private void registerBatteryReceiver() {
		if (this.mBatteryReceiver == null) {
			this.mBatteryReceiver = new BroadcastReceiver() {
				@Override public void onReceive(Context context, Intent intent) {
					try {
						Log.i("mBatteryReceiver onReceive");
						int i = intent.getExtras().getInt(MapBundleKey.MapObjKey.OBJ_LEVEL);
						App.this.mBatteryPercent = (i * 100) / intent.getExtras().getInt("scale");
					} catch (Throwable e) {
						Log.e("mBatteryReceiver onReceive exception = ", e);
					}
				}
			};
		}
		registerReceiver(this.mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	}

	private void unregisterBatteryReceiver() {
		BroadcastReceiver broadcastReceiver = this.mBatteryReceiver;
		if (broadcastReceiver != null) {
			unregisterReceiver(broadcastReceiver);
			this.mBatteryReceiver = null;
		}
	}

	private void registerBluetoothStateReceiver() {
		if (this.mBluetoothStateReceiver == null) {
			this.mBluetoothStateReceiver = new BroadcastReceiver() {
				@Override public void onReceive(Context context, Intent intent) {
					if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF) == BluetoothAdapter.STATE_ON) {
						DeviceContext.startAndRefreshAutoConnector();
					}
				}
			};
		}
		registerReceiver(this.mBluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
	}

	private void unregisterBluetoothStateReceiver() {
		BroadcastReceiver broadcastReceiver = this.mBluetoothStateReceiver;
		if (broadcastReceiver != null) {
			unregisterReceiver(broadcastReceiver);
			this.mBluetoothStateReceiver = null;
		}
	}

	public void uploadBiciLocationWithPhone(boolean z) {
		if (networkState != Enums.NetworkState.disable && isUserSignin()) {
			Callback callback = new Callback() {
				@Override public void onResponse(Call call, Response response) throws IOException {
				}

				@Override public void onFailure(Call call, IOException iOException) {
					iOException.printStackTrace();
				}
			};
			if (((((float) (System.currentTimeMillis() - lastUploadBiciLocationTimestamp)) / 1000.0f) / 60.0f) / 10.0f < 1.0f && !z) {
				return;
			}
			MyHttpClient.uploadBiciLocation(callback, SharedManager.getInstance().getCurLatLngWithMP());
			lastUploadBiciLocationTimestamp = System.currentTimeMillis();
		}
	}

	public void initAppWithUIVisible() {
		if (this.isAppForeground()) {
			SyncTaskService.startSyncService(this, TASK_SYNC_POI_PHOTO, true);
			SyncTaskService.startSyncService(this, TASK_SYNC_WORKOUT, SharedManager.getInstance().getAutoUploadMode() == 2);
		}
		isAppLaunched = true;
		PostQueueService.checkAndSend(this, false, true);
		registerBatteryReceiver();
		LevelPermissionMgr.getInstance().loadLevelHP();
		Log.logv(Constants.TAG, "[MainActivity] startApp end");
	}

	public void stopRemoteService(Class cls) {
		stopService(new Intent(this, cls));
	}
}
